<?php
/*
 * @Author: your name
 * @Date: 2021-06-29 15:36:22
 * @LastEditTime: 2021-06-29 16:09:28
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \myframe_cms\app\Http\Controllers\Admin\TagController.php
 */

namespace App\Http\Controllers\Admin;

use myframe\Page;
use App\Tag;

class TagController extends CommonController
{
    
    // 分页查询所有tag
    public function index(Tag $tag)
    {
        $page  =$this->request->get('page', 1);
        $total = $tag->count();
        $size =2;
        $offset=($page-1)*$size;


        $data = $tag->orderBy('sort', 'DESC')->limit($offset, $size)->get();

        $this->assign('tag', $data);

        $this->assign('page_html', Page::html('?page=', $total, $page, $size));

        return $this->fetch('admin/tag_list');
    }
    // 查询一条tag
    public function edit(Tag $tag)
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = $tag->where('id', $id)->first();
            $this->assign('id', $id);
            $this->assign('data', $data);
        }

        return $this->fetch('admin/tag_edit');
    }
    // 新增 或者修改 一条tag
    public function save(Tag $tag)
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');

    
        if ($status=='') {
            $status=0;
        } else {
            $status=1;
        }

        $data=[
            'name'=>$this->request->post('name', ''),
            'sort'=>$this->request->post('sort', 0),
            'status'=>$status
              ];
        if ($id) {
            $tag->where('id', $id)->update($data);
            $this->success('修改完成');
        } else {
            $tag->insert($data);
            $this->success('添加成功');
        }
    }

    // 删除一个 tag
    public function delete(Tag $tag)
    {
        $id=$this->request->get('id');
        $res= $tag->where('id', $id)->delete();
        if ($res) {
            $this->success('删除成功！');
        }
    }
}
